import { componentInfoType, ComponentsStateType } from '.'

export function getNextSelectedId(selectedId: string, componentsList: componentInfoType[]) {
  // 不计算被隐藏的
  const visibleComponents = componentsList.filter(item => !item.isHidden)
  // 找到当前选中组件的索引
  const index = visibleComponents.findIndex(item => item._id === selectedId)
  if (index >= 0) {
    // 如果只有一个组件，则清空选中组件
    if (visibleComponents.length <= 1) return ''
    // 如果选中的是最后一个组件，选中上一个
    if (index === visibleComponents.length - 1) return visibleComponents[index - 1]._id
    // 否则选中下一个组件
    return visibleComponents[index + 1]._id
  } else {
    return ''
  }
}

export function insertNewComponent(draft: ComponentsStateType, newComponent: componentInfoType) {
  if (draft.selectedId) {
    const index = draft.componentsList.findIndex(item => item._id === draft.selectedId)
    draft.componentsList.splice(index + 1, 0, newComponent)
  } else {
    draft.componentsList.push(newComponent)
  }
  // 设置选中最新加进来的组件
  draft.selectedId = newComponent._id
}
